<template>
	<el-main class="bg edit_wrap">
		<el-form ref="form" :model="form" status-icon label-width="120px" v-if="is_view()">
			<el-col v-if="user_group === '管理员' || $check_field('get','meeting_id') || $check_field('add','meeting_id') || $check_field('set','meeting_id')" 
				:xs="24" :sm="12" :lg="8" class="el_form_item_warp">
				<el-form-item label="会议" prop="meeting_id">
					<el-select id="meeting_id" v-model.number="form['meeting_id']" placeholder="请选择会议" filterable clearable
						v-if="user_group === '管理员' || (form['call_for_papers_id'] && $check_field('set','meeting_id')) || (!form['call_for_papers_id'] && $check_field('add','meeting_id'))" 
						:disabled="disabledObj['meeting_id_isDisabled']" @visible-change="loadMeetings">
						<el-option 
							v-for="meeting in meetingList" 
							:key="meeting.meeting_information_id" 
							:label="`${meeting.meeting_number} - ${$getBilingualText(meeting.conference_name)}`" 
							:value="meeting.meeting_information_id">
						</el-option>
					</el-select>
					<div v-else-if="$check_field('get','meeting_id')">{{getMeetingDisplay(form['meeting_id'])}}</div>
				</el-form-item>
			</el-col>
		<el-col v-if="user_group === '管理员' || $check_field('get','track_name') || $check_field('add','track_name') || $check_field('set','track_name')" 
			:xs="24" :sm="12" :lg="8" class="el_form_item_warp">
			<el-form-item label="主题名称" prop="track_name">
				<BilingualInput 
					v-if="user_group === '管理员' || (form['call_for_papers_id'] && $check_field('set','track_name')) || (!form['call_for_papers_id'] && $check_field('add','track_name'))"
					v-model="form['track_name']"
					field="track_name"
					label="主题名称"
					input-type="input"
					:input-props="{placeholder: '如：Track 1: 前沿人工智能基础'}"
					:disabled="disabledObj['track_name_isDisabled']"
				/>
				<div v-else-if="$check_field('get','track_name')">{{$getBilingualText(form['track_name'])}}</div>
			</el-form-item>
		</el-col>
			<el-col v-if="user_group === '管理员' || $check_field('get','display_order') || $check_field('add','display_order') || $check_field('set','display_order')" 
				:xs="24" :sm="12" :lg="8" class="el_form_item_warp">
				<el-form-item label="显示顺序" prop="display_order">
					<el-input-number id="display_order" v-model.number="form['display_order']" :min="0"
						v-if="user_group === '管理员' || (form['call_for_papers_id'] && $check_field('set','display_order')) || (!form['call_for_papers_id'] && $check_field('add','display_order'))" 
						:disabled="disabledObj['display_order_isDisabled']"></el-input-number>
					<div v-else-if="$check_field('get','display_order')">{{form['display_order']}}</div>
				</el-form-item>
			</el-col>
			
			<!-- 主题内容动态编辑 -->
			<el-col v-if="user_group === '管理员' || $check_field('get','topics') || $check_field('add','topics') || $check_field('set','topics')" 
				:xs="24" :sm="24" :lg="24" class="el_form_item_warp">
				<el-form-item label="主题内容" prop="topics">
					<div v-if="user_group === '管理员' || (form['call_for_papers_id'] && $check_field('set','topics')) || (!form['call_for_papers_id'] && $check_field('add','topics'))">
						<el-row :gutter="20" class="topics-grid">
							<el-col :xs="24" :sm="24" :md="24" v-for="(topic, index) in topicsList" :key="index" class="topic-item">
								<el-card shadow="hover" class="topic-card">
									<div slot="header" style="display: flex; justify-content: space-between; align-items: center;">
										<span>主题 {{ index + 1 }}</span>
										<el-button type="danger" size="mini" icon="el-icon-delete" circle @click="removeTopic(index)"></el-button>
									</div>
									<el-tabs v-model="topic.activeTab" type="border-card" size="small" class="bilingual-tabs">
										<el-tab-pane label="中文" name="zh" class="tab-pane-content">
											<el-input v-model="topic.zh" type="textarea" :rows="8" placeholder="请输入主题（中文）" @input="updateTopicsString" class="topic-textarea"></el-input>
										</el-tab-pane>
										<el-tab-pane label="English" name="en" class="tab-pane-content">
											<el-input v-model="topic.en" type="textarea" :rows="8" placeholder="Please enter topic (English)" @input="updateTopicsString" class="topic-textarea"></el-input>
										</el-tab-pane>
									</el-tabs>
								</el-card>
							</el-col>
						</el-row>
						<div style="margin-top: 20px;">
							<el-button size="small" icon="el-icon-plus" @click="addNewTopic">添加主题</el-button>
						</div>
					</div>
					<div v-else-if="$check_field('get','topics')">
						<el-tag v-for="(topic, index) in topicsList" :key="index" style="margin: 5px;">
							{{ $getBilingualText(JSON.stringify(topic)) }}
						</el-tag>
					</div>
				</el-form-item>
			</el-col>

			<el-col :xs="24" :sm="12" :lg="8" class="el_form_btn_warp">
				<el-form-item>
					<el-button type="primary" @click="submit()">提交</el-button>
					<el-button @click="cancel()">取消</el-button>
				</el-form-item>
			</el-col>
		</el-form>
	</el-main>
</template>

<script>
	import mixin from "@/mixins/page.js";

	export default {
		mixins: [mixin],
		data() {
			return {
				field: "call_for_papers_id",
				url_add: "~/api/call_for_papers/add?",
				url_set: "~/api/call_for_papers/set?",
				url_get_obj: "~/api/call_for_papers/get_obj?",
				url_upload: "~/api/call_for_papers/upload?",

				query: {
					"call_for_papers_id": 0,
				},

				form: {
					"meeting_id": 0,
					"track_name": '', // JSON格式: {"zh": "中文", "en": "English"}
					"topics": '', // JSON数组格式: ["主题1", "主题2"]
					"display_order": 0,
					"call_for_papers_id": 0,
				},
				disabledObj:{
					"meeting_id_isDisabled": false,
					"track_name_isDisabled": false,
					"topics_isDisabled": false,
					"display_order_isDisabled": false,
				},
				topicsList: [], // 格式: [{zh: "中文", en: "English", activeTab: "zh"}, ...]
				meetingList: [], // 会议列表
			}
		},
		methods: {
			/**
			 * 加载会议列表
			 */
			async loadMeetings(visible) {
				if (visible && this.meetingList.length === 0) {
					try {
						const json = await this.$get("~/api/meeting_information/get_list?size=1000");
						if (json.result && json.result.list) {
							this.meetingList = json.result.list;
						}
					} catch (e) {
						console.error('加载会议列表失败:', e);
					}
				}
			},
			
			/**
			 * 获取会议显示文本
			 */
			getMeetingDisplay(meetingId) {
				if (!meetingId) return '';
				const meeting = this.meetingList.find(m => m.meeting_information_id === meetingId);
				if (meeting) {
					return `${meeting.meeting_number} - ${this.$getBilingualText(meeting.conference_name)}`;
				}
				return meetingId;
			},
			
			get_obj_after(json) {
				if (json.result && json.result.obj) {
					this.parseTopicsFromString(json.result.obj.topics);
					// 加载会议列表以便显示
					if (json.result.obj.meeting_id) {
						this.loadMeetings(true);
					}
				}
			},
			parseTopicsFromString(str) {
				if (!str) {
					this.topicsList = [];
					return;
				}
				try {
					const topics = JSON.parse(str);
					// 兼容旧数据格式（字符串数组）和新格式（双语对象数组）
					if (Array.isArray(topics)) {
						// 保存当前每个主题的 activeTab 状态
						const currentActiveTabs = {};
						this.topicsList.forEach((topic, index) => {
							currentActiveTabs[index] = topic.activeTab || 'zh';
						});
						
						this.topicsList = topics.map((topic, index) => {
							// 保留原有的 activeTab，如果没有则默认为 'zh'
							const activeTab = currentActiveTabs[index] || 'zh';
							
							if (typeof topic === 'string') {
								// 旧格式：字符串，转换为双语格式
								return { zh: topic, en: '', activeTab: activeTab };
							} else if (typeof topic === 'object' && topic !== null) {
								// 新格式：双语对象
								return { zh: topic.zh || '', en: topic.en || '', activeTab: activeTab };
							}
							return { zh: '', en: '', activeTab: activeTab };
						});
					} else {
						this.topicsList = [];
					}
				} catch (e) {
					this.topicsList = [];
				}
			},
			removeTopic(index) {
				this.topicsList.splice(index, 1);
				this.updateTopicsString();
			},
			/**
			 * 添加新主题（直接显示双语输入区域）
			 */
			addNewTopic() {
				// 直接添加一个新的主题对象，包含双语输入区域
				this.topicsList.push({ 
					zh: '', 
					en: '', 
					activeTab: 'zh' 
				});
				this.updateTopicsString();
				// 滚动到新添加的主题
				this.$nextTick(() => {
					const cards = document.querySelectorAll('.el-card');
					if (cards.length > 0) {
						cards[cards.length - 1].scrollIntoView({ behavior: 'smooth', block: 'nearest' });
					}
				});
			},
			updateTopicsString() {
				// 只保存 zh 和 en 字段，不保存 activeTab
				const topicsToSave = this.topicsList.map(topic => ({
					zh: topic.zh || '',
					en: topic.en || ''
				}));
				this.form.topics = JSON.stringify(topicsToSave);
			},
			// 提交前处理
			submit_before(param) {
				// 确保topics字段是JSON字符串
				this.updateTopicsString();
				param.topics = this.form.topics;
				return param;
			},
			is_view(){
				var bl = this.user_group == "管理员";

				if(!bl){
					bl = this.$check_action('/call_for_papers/table','add');
					console.log(bl ? "你有表格添加权限视作有添加权限" : "你没有表格添加权限");
				}
				if(!bl){
					bl = this.$check_action('/call_for_papers/table','set');
					console.log(bl ? "你有表格添加权限视作有修改权限" : "你没有表格修改权限");
				}
				if(!bl){
					bl = this.$check_action('/call_for_papers/view','add');
					console.log(bl ? "你有视图添加权限视作有添加权限" : "你没有视图添加权限");
				}
				if(!bl){
					bl = this.$check_action('/call_for_papers/view','set');
					console.log(bl ? "你有视图修改权限视作有修改权限" : "你没有视图修改权限");
				}
				if(!bl){
					bl = this.$check_action('/call_for_papers/view','get');
					console.log(bl ? "你有视图查询权限视作有查询权限" : "你没有视图查询权限");
				}

				console.log(bl ? "具有当前页面的查看权，请注意这不代表你有字段的查看权" : "无权查看当前页，请注意即便有字段查询权限没有页面查询权限也不行");

				return bl;
			},
		},
		watch: {
			'form.topics': {
				handler(newVal, oldVal) {
					// 只在初始化或外部数据变化时解析，避免用户输入时重新解析导致标签切换
					// 如果 oldVal 为 undefined，说明是初始化
					// 如果 newVal 和 oldVal 都是字符串且内容相同，说明是用户输入触发的，不需要重新解析
					if (newVal && typeof newVal === 'string') {
						// 只在初始化时解析，或者当数据确实从外部变化时（比如从服务器加载）
						if (oldVal === undefined || (oldVal !== undefined && newVal !== oldVal && this.topicsList.length === 0)) {
							this.parseTopicsFromString(newVal);
						}
					}
				},
				immediate: true
			}
		}
}
</script>
<style scoped>
.topics-grid {
	margin-bottom: 20px;
}

.topic-item {
	margin-bottom: 20px;
}

.topic-card {
	display: flex;
	flex-direction: column;
	min-height: 300px;
}

.topic-card >>> .el-card__body {
	flex: 1;
	display: flex;
	flex-direction: column;
	padding: 15px;
}

.topic-card >>> .el-tabs {
	flex: 1;
	display: flex;
	flex-direction: column;
}

.topic-card >>> .el-tabs__content {
	flex: 1;
	min-height: 250px;
}

.topic-card >>> .el-tab-pane {
	height: 100%;
	min-height: 250px;
}

.topic-card >>> .el-textarea {
	width: 100%;
	height: 100%;
}

.topic-card >>> .el-textarea__inner {
	height: 100%;
	min-height: 200px;
	resize: vertical;
}

.topic-textarea {
	width: 100%;
}

.topic-textarea >>> .el-textarea__inner {
	min-height: 200px;
	font-size: 14px;
	line-height: 1.5;
	resize: vertical;
}

/* 优化标签页宽度，确保两个标签同时显示 */
.bilingual-tabs >>> .el-tabs__header {
	margin: 0;
}

.bilingual-tabs >>> .el-tabs__nav-wrap {
	overflow: visible;
}

.bilingual-tabs >>> .el-tabs__nav {
	width: 100%;
	display: flex;
}

.bilingual-tabs >>> .el-tabs__item {
	flex: 1;
	text-align: center;
	padding: 0 15px;
	min-width: 0;
}

.bilingual-tabs >>> .el-tabs__active-bar {
	display: none;
}

.bilingual-tabs >>> .el-tabs__item.is-active {
	border-bottom: 2px solid #409eff;
	color: #409eff;
	font-weight: 500;
}

.bilingual-tabs >>> .el-tabs__content {
	padding: 15px;
}

/* 响应式布局调整 */
@media (max-width: 768px) {
	.topic-item {
		margin-bottom: 15px;
	}
	
	.bilingual-tabs >>> .el-tabs__item {
		padding: 0 10px;
		font-size: 14px;
	}
}
</style>

